package com.ciwong.epaper.modules.clazz.ui;

import android.Manifest;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import com.android.volley.TimeoutError;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.clazz.adapter.TeacherClassAdapter;
import com.ciwong.epaper.modules.clazz.bean.StudentBean;
import com.ciwong.epaper.modules.clazz.bean.TeacherClassBean;
import com.ciwong.epaper.modules.cordva.html.BaseHtmlFragment;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.me.RefreshClass;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.HttpRequest;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.libs.utils.volley.BaseRequest;
import com.ciwong.mobilelib.bean.SchoolDetail;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.i.OnItemClickListener;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.widget.listview.PullRefreshController;
import com.ciwong.mobilelib.widget.listview.PullRefreshListView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 班级
 * Created by paul
 */
public class ClazzFragment extends BaseHtmlFragment implements PullRefreshController.PullRefreshListener {

    private List<TeacherClassBean> teacherClassBeans;

    private String clientId;
    private String userId;
    private String brandId;
    private int userRole = 2;

    /**
     * 可扩展ListView
     */
    private PullRefreshListView tea_class_pull_list;

    private TeacherClassAdapter teacherClassAdapter;
    //学生集合
    private List<StudentBean> studentBeans;

    public static ClazzFragment newInstance() {
        ClazzFragment fragment = new ClazzFragment();
        return fragment;
    }


    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_teacher_class, container, false);
        EventBus.getDefault().register(this);
        init(view);
        return view;
    }

    protected void init(View view) {
        BaseRequest.VerifyInfo verifyInfo = HttpRequest.getVerifyInfo();
        if (verifyInfo != null) {
            clientId = verifyInfo.getClientId();
            userId = EApplication.getInstance().getUserInfoBase().getUserId() + "";
            brandId = EApplication.BRAND_ID + "";
        }

        tea_class_pull_list = view.findViewById(R.id.tea_class_pull_list);
        tea_class_pull_list.setPullRefreshListener(this);
        tea_class_pull_list.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void avertRepeatOnClick(AdapterView<?> adapterView, View view, int i, long l) {
                try {
                    TeacherClassBean item = (TeacherClassBean) adapterView.getAdapter().getItem(i);
                    SchoolDetail mySchool = EApplication.getInstance().getMySchool();
                    if (null != mySchool) {
                        MeJumpManager.jumpToGroupingStuActivity(R.string.go_back, item.getClassId(), item.getClassName(), clientId, mySchool.getSchoolName(), item.getGradeId(), mActivity);
                    }
                } catch (Exception e) {

                }
            }
        });

        //loadData();
        //获取缓存到本地的数据
        loadLocalData(SerializableManager.SerializeKey.SHARE_KEY_CLAZZ_LIST + userId);

    }


    @Override
    protected void loadData() {
        //showCricleProgress();
        //getMyOneSchool();
    }


    /**
     * 获取学校信息
     */
    public void getMyOneSchool() {
        SchoolDetail mySchool = EApplication.getInstance().getMySchool();
        if (null == mySchool) {
            return;
        }
        getMyClass(brandId, userRole, mySchool.getSchoolId());
    }


    /**
     * 获取班级列表
     */
    public void getMyClass(String brandId, int userRole, int schoolId) {
        EpaperDao.getInstance().getMyClass(brandId, userRole, schoolId, new BaseExtCallBack(getActivity(), EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
                hideCricleProgress();
                tea_class_pull_list.stopLoadMore();
                tea_class_pull_list.stopRefresh();
                if (data instanceof TimeoutError) {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                } else {
                    if (!NetworkUtils.isOnline()) {
                        ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                        return;
                    }
                }
            }

            @Override
            public void failed(Object data) {
                tea_class_pull_list.stopLoadMore();
                tea_class_pull_list.stopRefresh();
                hideCricleProgress();
                if (!NetworkUtils.isOnline()) {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                    return;
                }
            }

            @Override
            public void success(Object data) {
                hideCricleProgress();
                tea_class_pull_list.stopRefresh();
                tea_class_pull_list.stopLoadMore();
                if (null != data && data instanceof ArrayList) {
                    teacherClassBeans = (List<TeacherClassBean>) data;
                    for (int i = 0; i < teacherClassBeans.size(); i++) {
                        getMembers(teacherClassBeans.get(i).getClassId(), 1, 1, 1, teacherClassBeans.get(i), i);
                    }

                }
            }
        });
    }


    /**
     * 获取班级成员
     *
     * @param classId
     * @param getIntegral
     * @param getVip
     * @param role
     */
    public void getMembers(int classId, int getIntegral, int getVip, int role, final TeacherClassBean teacherClassBean, final int index) {

        EpaperDao.getInstance().getmembers(classId, clientId, getIntegral, getVip, role, new BaseExtCallBack(getActivity(), EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
                hideCricleProgress();
                if (!NetworkUtils.isOnline()) {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                    return;
                }
            }

            @Override
            public void failed(Object data) {
                hideCricleProgress();
                if (data instanceof TimeoutError) {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                } else {
                    if (!NetworkUtils.isOnline()) {
                        ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                        return;
                    }
                }
            }

            @Override
            public void success(Object data) {
                hideCricleProgress();
                int vipCount = 0;
                if (null != data && data instanceof ArrayList) {
                    studentBeans = (List<StudentBean>) data;
                    Map<Integer, String> map = new HashMap<>();
                    for (StudentBean stu : studentBeans) {
                        if (stu.getIsVip() == 1) {
                            vipCount++;
                        }
                        map.put(stu.getTeamId(), stu.getTeamName());
                    }
                    /*Set<Integer> integers = map.keySet();
                    for (Integer integer : integers) {
                        List<StudentBean> stuList = new ArrayList<>();
                        for (int i = 0; i < studentBeans.size(); i++) {
                            if (studentBeans.get(i).getTeamId() == integer) {
                                stuList.add(studentBeans.get(i));
                            }
                        }
                        studentBeanLists.add(stuList);
                    }*/
                    teacherClassBean.setVipCount(vipCount);
                    if (index == teacherClassBeans.size() - 1) {
                        //将班级列表缓存本地
                        SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_CLAZZ_LIST + userId, (Serializable) teacherClassBeans);
                        setClass(teacherClassBeans);
                    }
                }
            }
        });
    }

    /**
     * 获取本地数据
     *
     * @param key
     */
    public void loadLocalData(String key) {

        showCricleProgress();
        SerializableManager.getInstance().deSerialize(key, new BaseCallBack() {
            @Override
            public void success(Object data) {
                hideCricleProgress();
                if (null != data) {
                    teacherClassBeans = (List<TeacherClassBean>) data;
                    setClass(teacherClassBeans);
                }

            }

            @Override
            public void failed(int errorCode, Object data) {
                //获取失败 请求接口
                getMyOneSchool();
            }

            @Override
            public void failed(Object data) {
                //获取失败 请求接口
                getMyOneSchool();
            }
        });

    }

    /**
     * 设置适配器数据
     *
     * @param teacherClassBeans
     */
    private void setClass(List<TeacherClassBean> teacherClassBeans) {
        teacherClassAdapter = new TeacherClassAdapter(mActivity, teacherClassBeans, clientId);
        tea_class_pull_list.setAdapter(teacherClassAdapter);
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        tea_class_pull_list.setPullRefreshEnable(true);
        tea_class_pull_list.setPullLoadEnable(true);
        tea_class_pull_list.setPullRefreshListener(this);
        tea_class_pull_list.hideFooter();
    }

    public void onEventMainThread(RefreshClass refreshNewBookDesk) {
        if (refreshNewBookDesk.isRefreshUnconditional()) {
            showCricleProgress();
            getMyOneSchool();
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onRefresh() {
        showCricleProgress();
        getMyOneSchool();
    }

    @Override
    public void onResume() {
        super.onResume();
        //loadData();
    }

    @Override
    public void onLoadMore() {

    }
}
